package com.yeyks.task;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yeyks.activity.dal.domain.ActivityNodeUserRecord;
import com.yeyks.activity.dal.domain.ActivityNoviceTask;
import com.yeyks.activity.service.ActivityNodeUserRecordService;
import com.yeyks.activity.service.ActivityNoviceTaskService;
import com.yeyks.common.constants.OrderStatus;
import com.yeyks.common.em.OrderStatusEnum;
import com.yeyks.common.utils.DateUtils;
import com.yeyks.commonReference.append.sms.SmsService;
import com.yeyks.commonReference.service.account.AccountCommissionService;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.commonReference.service.hotel.HotelAccountBillService;
import com.yeyks.commonReference.service.hotel.HotelInfoService;
import com.yeyks.commonReference.service.order.OrderHeadService;
import com.yeyks.commonReference.service.user.UserCommissionService;
import com.yeyks.order.dal.domain.OrderHead;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shuai
 * @date 2019/10/28 13:28
 */
@Component
@Slf4j
public class OrderCompleteTask {
    @Autowired
    private OrderHeadService orderHeadService;
    @Autowired
    private ConfigService configService;
    @Autowired
    private HotelAccountBillService hotelAccountBillService;
    @Autowired
    private HotelInfoService hotelInfoService;
    @Autowired
    private UserCommissionService userCommissionService;
    @Autowired
    private AccountCommissionService accountCommissionService;
    @Autowired
    private ActivityNoviceTaskService activityNoviceTaskService;
    @Autowired
    private ActivityNodeUserRecordService recordService;
    @Autowired
    private SmsService smsService;

    @Scheduled(cron = "${schedule.order.checkOut}")
    public void orderComplete() {
        log.info("订单完成执行，time = {}", DateUtil.formatDateTime(new Date()));
        //查询出来所有待入住和待退款和入住中的订单（2,5,7）
        List<OrderHead> orderHeads = orderHeadService.list(new QueryWrapper<OrderHead>()
                .in(OrderHead.STATUS, OrderStatusEnum.PRECHECKIN.value(), OrderStatusEnum.LIVING.value()));
        if (orderHeads == null || orderHeads.size() == 0) {
            log.info("查询到的所有待入住和待退款和入住中的订单数为空");
            return;
        }
        Date nowDate = new Date();
        //过滤离店时间后12个小时小于当前时间的订单
        List<OrderHead> disposeOrderHeads = orderHeads.stream().filter(e -> DateUtils.dateCompareDate(nowDate, DateUtils.afterHoursToDate(e.getCheckOut(), 12L))).collect(Collectors.toList());
        if (disposeOrderHeads.size() == 0) {
            log.info("需要处理的订单数为空");
            return;
        }
        for (OrderHead orderHead : disposeOrderHeads) {
            //c2b订单新手任务
            if (orderHead.getVipFlag() == 0) {
                //修改新手任务状态
                updateTask(orderHead.getUserId(), orderHead.getContactPhone(), orderHead.getSnapshotTotalFee());
            }
            orderHead.setStatus(OrderStatusEnum.POSTCHECKOUT.value());
            if (orderHeadService.update(null, new UpdateWrapper<OrderHead>()
                    .set(OrderHead.SNAPSHOT_REFUND_FEE, null)
                    .set(OrderHead.STATUS, OrderStatusEnum.POSTCHECKOUT.value())
                    .eq(OrderHead.ORDER_NO, orderHead.getOrderNo()))) {
                log.info("修改订单状态为已完成成功{}", orderHead.getOrderNo());
                //c2b和b2c订单给该下单用户的上级以及上上级分钱
                if (orderHead.getVipFlag() == 0 || orderHead.getVipFlag() == 2) {
                    userCommissionService.addZeroAmount(orderHead);
                }
                //精选订单佣金入账
                else if (orderHead.getVipFlag() == 3 && "yyks".equals(orderHead.getSourceType())) {
                    accountCommissionService.setMiniVipCommission(orderHead);
                } else {//c2b的话判断是否是第一单(设置免佣期使用)
                    int count = orderHeadService.orderCount(orderHead.getHotelId(), orderHead.getVipFlag(), 3);
                    if (1 == count) {
                        hotelInfoService.setNoFeeDateAtFirstOrder(orderHead.getHotelId(), orderHead.getGmtCreate());
                    }
                }
            } else {
                log.error("修改订单状态为已完成失败{}", orderHead.getOrderNo());
            }
        }
        //过滤掉甄选酒店的单和小于某个点的单，写入酒店订单账户信息
        Date overTime = configService.getHotelDate();
        List<OrderHead> c2bOrders = disposeOrderHeads.stream().filter(e -> (e.getVipFlag() == 0 || e.getVipFlag() == 2) && "yyks".equals(e.getSourceType()) && DateUtils.dateCompareDate(DateUtils.afterHoursToDate(e.getCheckOut(), 12L), overTime)).collect(Collectors.toList());
        if (!hotelAccountBillService.insertHotelAccountBill(c2bOrders)) {
            log.info("写入酒店订单账户信息失败");
        }
        log.info("订单完成执行end");
    }

    /**
     * 修改新手任务状态
     *
     * @param userId
     * @param phone
     * @param total
     */
    public void updateTask(Integer userId, String phone, Integer total) {
        //任务一：首先判断是否是第一单，是第一单的话判断金额是否满足任务二和任务三
        int count = orderHeadService.count(new QueryWrapper<OrderHead>()
                .eq(OrderHead.USER_ID, userId)
                .in(OrderHead.STATUS, OrderStatus.postCheckOut, OrderStatus.comment));
        //是第一单，奖励3元
        if (count == 0) {
            //第一笔
            dispose(userId, phone, 2, 300);
        }
        //非第一单，判断任务二，是否满足200不满足300元，奖励3元
        if (total >= 20000 && total < 30000) {
            //任务二成立
            dispose(userId, phone, 3, 300);
        }
        if (total >= 30000) {
            //任务三成立
            dispose(userId, phone, 4, 500);
        }

    }

    /**
     * @param userId
     * @param phone
     * @param type   2 第一单，3 大于等于200小于300，4 大于等于300
     * @param amount
     */
    private void dispose(Integer userId, String phone, Integer type, Integer amount) {
        //查询该用户新手任务活动
        ActivityNoviceTask one = activityNoviceTaskService.getOne(new QueryWrapper<ActivityNoviceTask>()
                .eq(ActivityNoviceTask.USER_ID, userId)
                .eq(ActivityNoviceTask.TYPE, type)
                .eq(ActivityNoviceTask.STATUSA, 1)
                .last("limit 1")
        );
        if (null == one) {
            if (4 == type) {
                type = 3;
                one = activityNoviceTaskService.getOne(new QueryWrapper<ActivityNoviceTask>().eq(ActivityNoviceTask.USER_ID, userId).eq(ActivityNoviceTask.TYPE, type).eq(ActivityNoviceTask.STATUSA, 1).last("limit 1"));
            }
        }
        if (null == one) {
            log.info("该用户没有参与新手任务活动userId = {}", userId);
        } else {
            one.setStatusa(2).setUpdateTime(new Date());
            boolean flag = activityNoviceTaskService.updateById(one);
            if (flag) {
                //发短信和写节点表记录
                if (recordService.save(new ActivityNodeUserRecord().setActivityCode("NewUserTask").setNode("finish_" + type).setUserId(userId).setCreateTime(new Date()))) {
//                        String phone = userInfoService.getPhoneById(userId);
                    if (null != phone) {
                        smsService.sendNewTask(phone, amount);
                    }
                }
            }
        }
    }
}
